package com.yumeko.boot;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @program: myTomcat_zhenghao
 * @description:加载外部类工具
 * @author: Zheng Hao
 * @create: 2020-02-16 15:58
 */
public class MyClassLoader extends ClassLoader {
    private URI myPath;

    public MyClassLoader(String name, ClassLoader parent, URI myPath) {
        super(name, parent);
        this.myPath = myPath;
    }

    public MyClassLoader(ClassLoader parent, URI myPath) {
        super(parent);
        this.myPath = myPath;
    }

    public MyClassLoader(URI myPath) {
        this.myPath = myPath;
    }

    @Override
    protected Class<?> findClass(String name) {
        //String myPath = "file:///D:/webapps/demo1/com/yumeko/YumekoServlet.class";
        //System.out.println(myPath);
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(myPath);
            cLassBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }

    public URI getMyPath() {
        return myPath;
    }

    public void setMyPath(URI myPath) {
        this.myPath = myPath;
    }

/*    public static void main(String[] args) {
        try {
            String path = "file:///D:/webapps/demo1/com/yumeko/YumekoServlet.class";
            MyClassLoader loader = new MyClassLoader(new URI(path));
            Class<?> aClass = loader.findClass("com.yumeko.YumekoServlet");
            Object obj = aClass.getConstructor().newInstance();
            Method method = aClass.getMethod("init");
            method.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
